using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using ChainAnalises.Classes.IntervalAnalysis;
using ChainAnalises.Classes.Root;
using ChainAnalises.Classes.Root.SimpleTypes;
using ChainAnalises.Classes.Statistics.MarkovChain.Generators;

namespace ChainAnalises.Classes.PhantomChains
{
    ///<summary>
    ///</summary>
    public class TreeNode:ITreeNode
    {
        private IBaseObject id = null;
        private ITreeNode Parent = null;


        ///<summary>
        ///</summary>
        ///<param name="Par"></param>
        ///<param name="content"></param>
        ///<param name="Table"></param>
        ///<exception cref="Exception"></exception>
        public TreeNode(ITreeNode Par, IBaseObject content, PhantomTable Table)
        {
            if (Par != null)
            {
                Parent = Par;
            }
            else
            {
                throw new Exception();
            }
            level = Parent.Level + 1;
            volume = Table[level + 1].Volume;
            id = content;
            StartPosition = Table.StartPositions[level];
        }

        ///<summary>
        ///</summary>
        ///<returns></returns>
        public override bool Decrement()
        {
            volume--;
            bool flag = Parent.Decrement();
            if (flag)
            {
                for (int i = 0; i < Children.Count; i++)
                {
                    if (Children[i].Volume == 0)
                    {
                        Children.RemoveAt(i);
                        return false;
                    }
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        ///<summary>
        ///</summary>
        ///<param name="Result"></param>
        ///<param name="Generator"></param>
        public void FillChain(BaseChain Result, IGenerator Generator,PhantomTable Table)
        {
            if ((Table.Length != (level + 2))&&(Children.Count==0))
            {
                MessagePhantom temp = Table[level + 2].Content;
                for (int i = 0; i < temp.power; i++)
                {
                    Children.Add(new TreeNode(this, temp[i], Table));
                }
            }
            if((id is BaseChain)||(id is ValueString))
            {
                String amin = id.ToString();
                for (int k = 0; k < amin.Length;k++)
                {
                    Result[StartPosition+k] = new ValueChar(amin[k]);
                }
            }
            else
            {
                Result[StartPosition] = id;
            }
            this.Find(Result,Generator,Table);
        }
    }
}